package com.sheep.jucdemo.part10.part10_1;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Date 2022/4/27 22:09
 * @Created by sheep
 */
public class Test10_1_2 {
    // 创建一个countDownLatch实例
    private static volatile CountDownLatch countDownLatch = new CountDownLatch(2);

    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        // 将线程A添加到线程池
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    System.out.println("child threadOne over");
                }catch (InterruptedException e){
                    e.printStackTrace();
                }finally {
                    countDownLatch.countDown();
                }
            }
        });
        // 将线程B添加到线程池
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    System.out.println("child threadTwo over");
                }catch (InterruptedException e){
                    e.printStackTrace();
                }finally {
                    countDownLatch.countDown();
                }
            }
        });
        System.out.println("wait all child thread over");
        // 等待子线程执行完毕，返回
        countDownLatch.await();

        System.out.println("all child thread over");
        executorService.shutdown();
        long end = System.currentTimeMillis();
        System.out.println("耗时：" + (end - start));
    }
}
